package com.android.yinghebike.ui.view;

import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.util.AttributeSet;
import android.view.View;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;

import com.android.baselibrary.tool.CommToast;
import com.android.baselibrary.tool.Log;
import com.android.baselibrary.util.DateUtil;
import com.android.yinghebike.R;
import com.android.yinghebike.bean.BleDataInfo;
import com.android.yinghebike.manager.BleManager;
import com.android.yinghebike.manager.UnitManager;
import com.android.yinghebike.ui.activity.Device_ListActivity;
import com.android.yinghebike.ui.fragment.HomeMainFragment;
import com.mapbox.navigation.base.trip.model.RouteProgress;
import com.mapbox.navigation.ui.tripprogress.model.TripProgressUpdateValue;

import java.util.List;
import java.util.UUID;

import cn.wandersnail.ble.Device;
import cn.wandersnail.ble.EasyBLE;
import cn.wandersnail.ble.EventObserver;
import cn.wandersnail.commons.util.StringUtils;

//导航页面-导航进度控件
public class Nav_ProgressView extends RelativeLayout {
    public Nav_ProgressView(Context context) {
        super(context);
        this.mContext = context;
        initView(null);
    }

    public Nav_ProgressView(Context context, AttributeSet attrs) {
        super(context, attrs);
        this.mContext = context;
        initView(attrs);
    }

    public Nav_ProgressView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        this.mContext = context;
        initView(attrs);
    }

    Context mContext;
    public TextView tv_speed, tv_exit, tv_power, tv_dangwei, tv_speed_unit;
    Home_InfoView hi_distance, hi_time;
    Nav_InfoView ni_bluetooth, ni_gonglv;
    ProgressBar pb_power;


    private void initView(AttributeSet attrs) {
        View.inflate(mContext, R.layout.view_nav_progress, this);
        tv_speed = findViewById(R.id.tv_speed);
        tv_exit = findViewById(R.id.tv_exit);
        hi_distance = findViewById(R.id.hi_distance);
        hi_time = findViewById(R.id.hi_time);
        ni_bluetooth = findViewById(R.id.ni_bluetooth);
        ni_gonglv = findViewById(R.id.ni_gonglv);
        pb_power = findViewById(R.id.pb_power);
        tv_power = findViewById(R.id.tv_power);
        tv_dangwei = findViewById(R.id.tv_dangwei);
        tv_speed_unit = findViewById(R.id.tv_speed_unit);

        tv_speed_unit.setText(UnitManager.getSpeedUnitText());

        EasyBLE.getInstance().registerObserver(eventObserver);

        ni_bluetooth.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                mContext.startActivity(new Intent(mContext, Device_ListActivity.class));
            }
        });
        checkBluetoothState();
    }

    @Override
    protected void onDetachedFromWindow() {
        super.onDetachedFromWindow();
        //注销
        EasyBLE.getInstance().unregisterObserver(eventObserver);
    }

    //点击退出导航
    public void setExitClick(OnClickListener clickListener) {
        tv_exit.setOnClickListener(clickListener);
    }

    //更新导航进度
    public void refreshProgress(RouteProgress routeProgress) {
        //剩余距离
        hi_distance.setContent(UnitManager.getDisplayDistanceByUnit(routeProgress.getDistanceRemaining()));
        //剩余时间
        hi_time.setContent(DateUtil.generateTimeAll((int) routeProgress.getDurationRemaining()));
    }

//    //更新导航进度
//    public void refreshProgress(TripProgressUpdateValue result) {
//        hi_distance.tv_content.setText(result.getFormatter().getDistanceRemaining(result.getDistanceRemaining()).toString());
//        hi_time.tv_content.setText(result.getFormatter().getTimeRemaining(result.getCurrentLegTimeRemaining()).toString());
//    }

    //蓝牙事件
    EventObserver eventObserver = new EventObserver() {
        @Override
        public void onConnectionStateChanged(@NonNull Device device) {
            EventObserver.super.onConnectionStateChanged(device);
            switch (device.getConnectionState()) {
                case SCANNING_FOR_RECONNECTION:

                    break;
                case CONNECTING:
                    Log.i("连接中...");
                    break;
                case DISCONNECTED:
                    Log.i("连接断开");
                    checkBluetoothState();
                    break;
                case SERVICE_DISCOVERED:
                    Log.i("连接成功");
                    checkBluetoothState();
                    break;
            }
        }

        @Override
        public void onCharacteristicChanged(@NonNull Device device, @NonNull UUID service, @NonNull UUID characteristic, @NonNull byte[] value) {
            String hexStr = StringUtils.toHex(value, " ");
            Log.w("收到数据：" + hexStr);
            //5E 12 02 80 00 00 00 00 00 00 00 00 00 00 00 00 F2 0D
            if (value[0] == 0x5E && value[value.length - 1] == 0x0D) {
                List<BleDataInfo> dataInfoList = BleManager.getInstance().parseData(value);
                switch (value[3]) {
                    case HomeMainFragment.Byte_Index_Speed:
                        bindData1(dataInfoList);
                        break;
                    case HomeMainFragment.Byte_Index_Mileage:
//                        bindData2(dataInfoList);
                        break;
                }
            }
        }
    };

    //根据蓝牙状态 显示不同图标，文字颜色
    private void checkBluetoothState() {
        if (BleManager.getInstance().isConnect()) {
            ni_bluetooth.tv_title.setText(getResources().getString(R.string.comm_connected));
            ni_bluetooth.tv_title.setTextColor(Color.WHITE);
            ni_bluetooth.iv_img.setImageResource(R.drawable.ico_home_main_device_yilianjie);
        } else {
            ni_bluetooth.tv_title.setText(getResources().getString(R.string.comm_unconnected));
            ni_bluetooth.tv_title.setTextColor(Color.parseColor("#FD6D41"));
            ni_bluetooth.iv_img.setImageResource(R.drawable.ico_home_main_device_weilianjie);
        }
    }

    //绑定实时速度
    private void bindData1(List<BleDataInfo> dataInfoList) {
        //计算速度
        int dangwei = BleDataInfo.getDataByIndex(dataInfoList, new byte[]{(byte) 0x01});
        int speed = BleDataInfo.getDataByIndex(dataInfoList, new byte[]{(byte) 0x02, (byte) 0x03});
        int gonglv = BleDataInfo.getDataByIndex(dataInfoList, new byte[]{(byte) 0x0a, (byte) 0x0b});
        int power = BleDataInfo.getDataByIndex(dataInfoList, new byte[]{(byte) 0x06});

        String speedStr = (UnitManager.getDisplaySpeedByUnit(speed / 10d)) + "";
        tv_speed.setText(speedStr);

        tv_dangwei.setText(dangwei + "");
        if (dangwei == 15) {
            tv_dangwei.setText("P");  //挡位如果是15，显示P
        }
        pb_power.setProgress(power);
        tv_power.setText(power + "%");
        ni_gonglv.setTv_title(gonglv + "");

    }

}
